package com.geek.thread.thread_pool;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**线程池测试*/
@Slf4j
public class ThreadPoolTest {

    private ThreadPoolExecutor executor;

    ThreadPoolTest(){
        this.create();
    }

    private void create(){
        int corePoolSize = 10; // 线程池长期维持的线程数，即使线程处于Idle状态，也不会回收。
        int maximumPoolSize = 20; // 线程数的上限
        // 超过corePoolSize的线程的idle时长，超过这个时间，多余的线程会被回收。
        long keepAliveTime = 10;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(100); // 任务的排队队列
        ThreadFactory threadFactory = new ThreadFactoryBuilder().build(); // 新线程的产生方式
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy(); // 拒绝策略
        this.executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
    }


    public void execute(Runnable r){
        executor.execute(r);
    }


    public static void main(String[] args) throws Exception {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        for (int i = 0; i < 1000; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    countDownLatch.await();
                    SimpleSingleton.getInstance().log(finalI);
//                    SimpleSingleton.resetInstance();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        countDownLatch.countDown();



    }

}
